package com.dzy.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.dzy.entity.UserInfo;
import com.dzy.result.Result;
import com.dzy.result.ResultCodeEnum;
import com.dzy.service.UserInfoService;
import com.dzy.util.MD5;
import com.dzy.util.ValidateCodeUtils;
import com.dzy.vo.LoginVo;
import com.dzy.vo.RegisterVo;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/userInfo")
public class UserInfoController {
    @Reference
    private UserInfoService userInfoService;

    @RequestMapping("/sendCode/{phone}")
    public Result sendCode(@PathVariable String phone, HttpServletRequest request) {
        //产生一个随机的验证码
        String code = ValidateCodeUtils.generateValidateCode4String(6);
        //将验证码存入session，用来判断验证码是否正确
        request.getSession().setAttribute("CODE", code);
        return Result.ok(code);
    }

    @RequestMapping("/register")
    public Result register(@RequestBody RegisterVo registerVo, HttpServletRequest request) {

        String nickName = registerVo.getNickName();
        String phone = registerVo.getPhone();
        String password = registerVo.getPassword();
        String code = registerVo.getCode();
        //判断表单项均不能为空（null ""）
        if (StringUtils.isEmpty(nickName) ||
                StringUtils.isEmpty(phone) ||
                StringUtils.isEmpty(password) ||
                StringUtils.isEmpty(code)) {
            return Result.build(null, ResultCodeEnum.PARAM_ERROR);
        }

        //判断验证码是否正确
        String code1 = (String) request.getSession().getAttribute("CODE");
        if (!code.equals(code1)) {
            return Result.build(null, ResultCodeEnum.CODE_ERROR);
        }
        //判断手机是否已经被注册
        UserInfo userInfo = this.userInfoService.getByPhone(phone);
        if (userInfo != null) {
            return Result.build(null, ResultCodeEnum.PHONE_REGISTER_ERROR);
        }

        //调用业务侧完成注册功能
        userInfo = new UserInfo();
        userInfo.setNickName(nickName);
        userInfo.setPhone(phone);
        //MD5非对称加密，无法解密，不同明文密文不同
        userInfo.setPassword(MD5.encrypt(password));
        userInfo.setStatus(1);
        int insert = this.userInfoService.insert(userInfo);
        //因为采用的不是Thymeleaf、JSP这样的服务器脚本，所以拿不到session的数据。所以通过Ajax返回用户名相关数据
        //再客户端页面的回调函数中，只显示不可以。还要保存到客户端本地。注销之前的所有页面都可以从本地获取
        return Result.ok();
    }

    @RequestMapping("login")
    public Result login(@RequestBody LoginVo loginVo, HttpServletRequest request) {
        String phone = loginVo.getPhone();
        String password = loginVo.getPassword();

        //校验参数
        if (StringUtils.isEmpty(phone) ||
                StringUtils.isEmpty(password)) {
            return Result.build(null, ResultCodeEnum.PARAM_ERROR);
        }

        UserInfo userInfo = userInfoService.getByPhone(phone);
        if (null == userInfo) {
            return Result.build(null, ResultCodeEnum.ACCOUNT_ERROR);
        }

        //校验密码
        if (!MD5.encrypt(password).equals(userInfo.getPassword())) {
            return Result.build(null, ResultCodeEnum.PASSWORD_ERROR);
        }

        //校验是否被禁用
        if (userInfo.getStatus() == 0) {
            return Result.build(null, ResultCodeEnum.ACCOUNT_LOCK_ERROR);
        }

        //登录成功，将用户的某些信息通过Ajax返回，在回调函数中进行处理，存储到客户端本地
        //已经报用户的信息传递到客户端并保存，为什么还要在服务器的session中保存用户信息
        //比如：关注房源后，获取了houseId，但是userId是谁，还要从session中获取
        request.getSession().setAttribute("USER", userInfo);

        Map<String, Object> map = new HashMap<>();
        map.put("phone", userInfo.getPhone());
        map.put("nickName", userInfo.getNickName());
        return Result.ok(map);
    }

    @RequestMapping("/logout")
    public Result logout(HttpServletRequest request) {
        //request.getSession().removeAttribute("USER");
        request.getSession().invalidate();//不仅removeAttribute("USER")，还remove了其他的Attribute，连整个session都失效
        return Result.ok();
    }

}
